<template>
  <div>
    <el-form
      label-position="left"
      :model="formData"
      style="max-width: 300px; margin: 50px auto"
    >
      <el-form-item label="账号" prop="userName">
        <el-input
          v-model.trim="formData.userName"
          placeholder="请输入账号"
        ></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input
          v-model="formData.password"
          placeholder="请输入密码"
          type="password"
        />
      </el-form-item>
      <div style="display: flex; justify-content: center">
        <el-button type="primary" @click="login" style="width: 100vw"
          >登录</el-button
        >
      </div>
      <div
        style="
          margin-top: 10px;
          display: flex;
          justify-content: center;
          cursor: pointer;
          color: #333;
          font-size: 14px;
        "
      >
        <div @click="updatePwd">忘记密码</div>
        <div style="margin: 0 10px">|</div>
        <div @click="zhuce">注册新账号</div>
      </div>
    </el-form>
  </div>
</template>
<script setup lang="ts">
import { onMounted, reactive } from "vue";
import _service from "../../service/host";
import { useRouter, useRoute } from "vue-router";
import { listenerCount } from "process";
const formData = reactive({
  userName: "",
  password: "",
});
const router = useRouter();
const route = useRoute();
onMounted(() => {
  console.log(route);
});
const zhuce = () => {
  router.push({
    path: "/register",
  });
};
const login = () => {
  _service
    .getDetail({
      userName: formData.userName,
      password: formData.password,
    })
    .then(() => {
      loginJump();
    })
    .catch((err) => {
      console.log(err);
      loginJump();
    });
};
const loginJump = () => {
  document.cookie = `userName=${formData.userName}`;
  const token = {
    token: `userName=${formData.userName}`,
    userName: formData.userName,
    expireDate: new Date().getTime() + 1000 * 60 * 10,
  };
  localStorage.setItem("token", JSON.stringify(token));
  ElMessage({
    message: "登录成功，跳转首页...",
    type: "success",
  });
  setTimeout(() => {
    const query = route.query;
    if (query.redirect) {
      let redirect = decodeURIComponent(query.redirect);
      if (redirect.includes("?")) {
        let [path, queryStr] = redirect.split("?");

        router.push({
          path: path,
          query: parseQuery(queryStr),
        });
        return;
      }
      router.push({
        path: redirect,
      });
      return;
    }
    router.push({
      path: "/",
    });
  }, 1500);
};
// http://localhost:8085/#/login?redirect=/test-props?aaa=1%26bb=2
const parseQuery = (str: string) => {
  const obj = {};
  str.split("&").forEach((item) => {
    let [key, value] = item.split("=");
    obj[key] = value;
  });
  return obj;
};

const updatePwd = () => {
  router.push({
    path: "/change-pwd",
  });
};
</script>
<style lang="scss" scoped></style>
